<template>
  <div>
    <el-input :value="value" style="display: none;" @input="updateParent">
    </el-input>
    <el-input ref="textInput" :placeholder="placeholder" :value="selectedText" @focus="openUserDialog">
      <i slot="suffix" class="el-input__icon el-icon-user"></i>
    </el-input>

    <user-dialog ref="userDialog" :role-id="roleId" :selected-value-str="value" :single-select="singleSelect"
      @dialogSelected="dialogSelect" :user="user" :role="role" />
  </div>

</template>

<script>
import UserDialog from './userDialog'
import { getUserName } from '../../api/system/user'

export default {
  name: 'UserInput',
  components: {
    UserDialog
  },
  props: {
    value: {
      type: String,
      require: true,
      default: ''
    },
    user: {
      type: Number
    },
    role: {
      type: Number
    },
    text: {
      type: String,
      require: true,
      default: ''
    },
    placeholder: {
      require: true,
      type: String
    },
    roleId: {
      type: Number,
      require: true
    },
    singleSelect: {
      type: Boolean,
        required: false,
        default: true
      }
    },
    data() {
      return {
        //选择用户后选中的值
        selectedValue: '',
        //选择用户后显示的文字
        selectedText: '',
        //选择用户对象
        selected: [],
        //用户弹窗是否显示
        open: false
      }
    },
    created() {
    this.selectedValue = this.value ? this.value : ''
    this.setUserName()
  },
    updated() {
    this.setUserName()
  },
    methods: {
      /**初始化*/
      init() {
      
      },
      /** 通过user接口获取用户名称 */
      setUserName() {
        if (this.value) {
          getUserName(this.value).then((response) => {
            if (200 === response.code) {
              this.selectedText = response.data

            }
          })
        } else {
          this.selectedText = ''
        }
      },
      /** 打开用户弹窗 */
      openUserDialog() {
        this.$refs['userDialog'].show()
      },
      /** 弹窗选择 */
      dialogSelect(selectedValueArr, selectedTextArr, selectedArr) {
        let selectedValueStr = JSON.parse(JSON.stringify(selectedValueArr)).join(',')
        let selectedTextStr = JSON.parse(JSON.stringify(selectedTextArr)).join(',')
        this.selectedValue = selectedValueStr
        this.selectedText = selectedTextStr
        this.updateParent(selectedValueStr)

        this.$emit('selected', selectedValueStr, selectedArr)
      },
      /** 更新父组件中的v-model*/
      updateParent(val) {
        this.$emit('input', val)
      }
    }
  }
</script>
